import { useState, useEffect } from "react";
import api from "./api/api";
import PodcastCard from "./PodcastCard";
import Accordion from "./Accordion";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";

const Home = () => {

  const [podcasts, setPodcasts] = useState([]);
  const history = useHistory();

  useEffect(() => {
    const fetchHomePagePodcasts = async () => {
      try {
        const baseUrl = api.getUri();
        const offset = 0;
        const limit = 3;
        const response = await api.get(`/podcasts?offset=${offset}&limit=${limit}`);
        let returnedPodcasts = response.data;
        returnedPodcasts = returnedPodcasts.map((podcast) => {
          podcast.coverUrl = `${baseUrl}/podcasts/${podcast.id}/cover`;
          return podcast;
        });
        setPodcasts(returnedPodcasts);
      }
      catch (err) {
        console.log(`Error:${err.message}`);
      }
    };
    fetchHomePagePodcasts();
  }, []);


  return (
    <div className="
        container
        min-h-100
        flex-fill
        "
    >
      <div className="container">

        <div className="text-center">
          <h1 className="my-3">
            <div className="display-5">倾听</div>
            <div className="display-3 text-primary">世界的声音</div>
          </h1>
        </div>

        <div className="row justify-content-center">

          {podcasts && podcasts.map(
            (podcast) => (<PodcastCard key={podcast.id} id={podcast.id} title={podcast.title} coverUrl={podcast.coverUrl} />)
          )}

        </div>

        <div className="text-center mt-4 mb-5">
          <button className="btn btn-outline-primary max-w-10" onClick={() => { history.push("/podcasts"); }}>浏览全部播客</button>
        </div>

        <div className="text-center my-5">
          <h1>
            <div className="display-5">让世界听到</div>
            <div className="display-3 text-primary">你的声音</div>
          </h1>
        </div>

        <Accordion />

      </div >
    </div >
  );
};

export default Home;
